﻿<%@ WebHandler Language="C#" Class="ZSTaskFinishRateDashBoard" %>

using System;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using ReportBusiness;
using System.Collections;
using System.IO;

/**
 * Description: 准时完成率统计看板
 * Copyright (c): 通力凯顿（北京）系统集成有限公司
 * Author: zhunan
 * Date: 2025.5.14
 */

public class ZSTaskFinishRateDashBoard : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//各单位计划准时完成率
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getDetailsData":
                        r = getDetailsData(jObject);//数据钻取
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "exportChartDetailData":
                        exportChartDetailData(jObject);//弹窗明细导出
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    string getSql(JObject obj)
    {
        string sql = @"
SELECT f.factoryname,w.workcentername,ep.mfgordername,ep.machineno,ep.productname,ep.containerno,ep.plannedstartdate,ep.plannedfinishdate,
       ep.finishdate,
       CASE WHEN ep.finishdate IS NULL AND SYSDATE - ep.plannedfinishdate > 0 THEN '超期未完成'
            WHEN ep.finishdate IS NULL AND SYSDATE <=  ep.plannedfinishdate THEN '未完成'
            WHEN ep.finishdate IS NOT NULL AND ep.finishdate > ep.plannedfinishdate THEN '超期完成'
            WHEN ep.finishdate IS NOT NULL AND ep.finishdate <= ep.plannedfinishdate THEN '按时完成' 
       END status
FROM enginepartplan ep
INNER JOIN workcenter w ON w.workcenterid = ep.workcenterid
LEFT JOIN containercurrentinfo cci ON cci.containerid = ep.containerid
LEFT JOIN factory f ON f.factoryid = cci.originalfactoryid
WHERE ep.containerno IS NOT NULL";
        //计划完成时间
        if (obj["plannedfinishdate"] != null && obj["plannedfinishdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(obj["plannedfinishdate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND ep.plannedfinishdate >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss')", arr[0].ToString());
                sql += string.Format(" AND ep.plannedfinishdate <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss')", arr[1].ToString());
            }
        }

        //分厂
        if (obj["factoryid"] != null && obj["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.originalfactoryid = '{0}'", obj["factoryid"].ToString());
        }

        //任务单号
        if (obj["containerno"] != null && obj["containerno"].ToString() != "")
        {
            sql += string.Format(" AND ep.containerno = '{0}'", obj["containerno"].ToString());
        }

        //零件图号
        if (obj["productname"] != null && obj["productname"].ToString() != "")
        {
            sql += string.Format(" AND ep.productname = '{0}'", obj["productname"].ToString());
        }

        //订单号
        if (obj["mfgordername"] != null && obj["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND ep.mfgordername = '{0}'", obj["mfgordername"].ToString());
        }

        //中心
        if (obj["workcentername"] != null && obj["workcentername"].ToString() != "")
        {
            sql += string.Format(" AND w.workcentername = '{0}'", obj["workcentername"].ToString());
        }

        //状态
        if (obj["seriesName"] != null && obj["seriesName"].ToString() != "")
        {
            string seriesName = obj["seriesName"].ToString();
            if (seriesName == "准时完成率")
            {
                sql += " AND ep.finishdate IS NOT NULL AND ep.finishdate <= ep.plannedfinishdate";
            }
            if (seriesName == "超期完成率")
            {
                sql += " AND ep.finishdate IS NOT NULL AND ep.finishdate > ep.plannedfinishdate";
            }
            if (seriesName == "超期未完成率")
            {
                sql += " AND ep.finishdate IS NULL AND SYSDATE - ep.plannedfinishdate > 0";
            }
        }
        return sql;
    }

    Result getData(JObject obj)
    {
        string sql = @"
SELECT t.workcentername,COUNT(1) qty,
       SUM(DECODE(t.status,'按时完成',1,0)) intimefinishcount,
       SUM(DECODE(t.status,'超期完成',1,0)) delayfinishcount,
       SUM(DECODE(t.status,'超期未完成',1,0)) delaynotfinishcount,
       ROUND(SUM(DECODE(t.status,'按时完成',1,0))/COUNT(1),4) * 100 intimefinishrate,
       ROUND(SUM(DECODE(t.status,'超期完成',1,0))/COUNT(1),4) * 100 delayfinishrate,
       ROUND(SUM(DECODE(t.status,'超期未完成',1,0))/COUNT(1),4) * 100 delaynotfinishrate
FROM 
(
  {0}
) t
GROUP BY t.workcentername";
        sql = string.Format(sql, getSql(obj));
        DataTable dtResult = dal.GetDataTable(sql);
        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dtResult;
        r.total = Convert.ToInt32(dtResult.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    Result getDetailsData(JObject obj)
    {
        string sql = getSql(obj);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)obj["currentPage"], (int)obj["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    void exportChartDetailData(JObject obj)
    {
        string sql = getSql(obj);
        DataTable dtResult = dal.GetDataTable(sql);

        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        dtResult.Columns["factoryname"].Caption = "分厂";
        dtResult.Columns["workcentername"].Caption = "中心";
        dtResult.Columns["mfgordername"].Caption = "订单号";
        dtResult.Columns["machineno"].Caption = "发动机号";
        dtResult.Columns["productname"].Caption = "零件号";
        dtResult.Columns["containerno"].Caption = "任务单号";
        dtResult.Columns["plannedstartdate"].Caption = "计划开始时间";
        dtResult.Columns["plannedfinishdate"].Caption = "计划完成时间";
        dtResult.Columns["finishdate"].Caption = "实际完成时间";
        dtResult.Columns["status"].Caption = "状态";

        ExportHelper.ExportExcel(dtResult, "准时完成率统计看板导出数据");
    }
}